<template>
  <div class="app-container">
    <el-card class="common-card query-box">
      <div class="queryForm">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item :label="$t('merchant.name')">
            <el-input
                v-model="queryParams.merchantName"
                :placeholder="$t('merchant.namePlaceholder')"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('merchant.status')">
            <el-select
                v-model="queryParams.status"
                :placeholder="$t('merchant.statusPlaceholder')"
                clearable
                style="width: 200px"
            >
              <el-option
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{ $t('jbx.text.query') }}</el-button>
            <el-button @click="resetQuery">{{ $t('jbx.text.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="common-card">
      <div class="btn-form">
        <el-button type="primary" @click="handleAdd">{{ $t('jbx.text.add') }}</el-button>
        <el-button @click="handleDeleteBatch" :disabled="ids.length === 0">{{ $t('jbx.text.deleteBatch') }}</el-button>
      </div>
      <el-table v-loading="loading" :data="merchantList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('merchant.id')" align="center" prop="id" />
        <el-table-column label="父级商户" align="center" prop="parentCode">
          <template #default="scope">
            {{ getParentMerchantName(scope.row.parentCode) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('merchant.name')" align="left" prop="merchantName" />
        <el-table-column :label="$t('merchant.code')" align="center" prop="merchantCode" />
        <el-table-column :label="$t('merchant.contact')" align="center" prop="contact" />
        <el-table-column :label="$t('merchant.phone')" align="center" prop="phone" />
        <el-table-column :label="$t('merchant.channel')" align="center" prop="channelCode" />
        <el-table-column :label="$t('merchant.address')" align="center" prop="address" :show-overflow-tooltip="true" />
        <el-table-column :label="$t('merchant.sortIndex')" align="center" prop="sortIndex" />
        <el-table-column :label="$t('merchant.status')" align="center" prop="status">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column :label="$t('jbx.text.createdDate')" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('jbx.text.action')" align="center" width="140">
          <template #default="scope">
            <el-button icon="View" link @click="handleView(scope.row)"></el-button>
            <el-button icon="Edit" link @click="handleUpdate(scope.row)"></el-button>
            <el-button icon="Delete" link @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 商户编辑对话框 -->
    <merchant-edit 
      :title="title" 
      :open="openEdit" 
      :form-id="formId"
      @dialogOfClosedMethods="dialogOfClosedMethods"
    />

    <!-- 商户详情对话框 -->
    <merchant-detail
      :title="detailTitle"
      :open="openView"
      :merchant-id="detailId"
      @update:open="openView = $event"
    />
  </div>
</template>

<script setup name="Merchant" lang="ts">
import { ref, getCurrentInstance, reactive, toRefs, onMounted } from "vue";
import { ElForm } from "element-plus";
import modal from "@/plugins/modal";
import { useI18n } from "vue-i18n";
import { parseTime } from "@/utils/Jinbooks";
import MerchantEdit from './edit.vue'
import MerchantDetail from './detail.vue'
import { listMerchant, delMerchant } from '@/api/merchant/merchant'

const { t } = useI18n();
const { proxy } = getCurrentInstance()!;

// 字典数据
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

// 定义变量
const merchantList = ref([]);
const merchantOptions = ref([]);
const openEdit = ref(false);
const openView = ref(false);
const loading = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref("");
const ids = ref<string[]>([]);
const formId = ref("");
const detailId = ref("");

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantName: undefined,
    status: undefined
  }
});

const { queryParams } = toRefs(data);
const queryRef = ref<InstanceType<typeof ElForm> | null>(null);

// 获取父级商户名称
const getParentMerchantName = (parentCode: string) => {
  if (!parentCode) {
    return '无'
  }
  
  const parent = merchantOptions.value.find((item: any) => item.merchantCode === parentCode)
  return parent ? parent.merchantName : '未知'
}

// 获取列表
function getList() {
  loading.value = true;
  listMerchant(queryParams.value).then((response: any) => {
    merchantList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    merchantList.value = [];
    total.value = 0;
  });
}

// 获取商户选项列表
const getMerchantOptions = () => {
  listMerchant({}).then((response: any) => {
    if (response.code === "0") {
      merchantOptions.value = response.data.records
    }
  })
}

// 页面加载时获取商户选项列表
getMerchantOptions()

// 查询
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 商户状态修改
function handleStatusChange(row) {
  let text = row.status === 1 ? t('jbx.text.enable') : t('jbx.text.disable');
  modal.confirm(t('jbx.confirm.text') + text + t('jbx.text.is') + t('merchant.name') + "“" + row.merchantName + "”？").then(function() {
    // 模拟修改状态
    modal.msgSuccess(t('jbx.alert.operate.success'));
    return Promise.resolve();
  }).catch(function() {
    row.status = row.status === 1 ? 0 : 1;
  });
}

// 新增
function handleAdd() {
  formId.value = "";
  openEdit.value = true;
  title.value = t('merchant.add');
}

// 修改
function handleUpdate(row) {
  const id = row.id;
  formId.value = id;
  openEdit.value = true;
  title.value = t('merchant.edit');
}

// 删除
function handleDelete(row) {
  const merchantIds = row.id;
  modal.confirm(t('jbx.confirm.text.delete')).then(function() {
    delMerchant([merchantIds]).then(() => {
      modal.msgSuccess(t('jbx.alert.delete.success'));
      getList();
    }).catch(() => {
      modal.msgError(t('jbx.alert.delete.failure'));
    });
    return Promise.resolve();
  }).catch(() => {});
}

// 批量删除
function handleDeleteBatch() {
  modal.confirm(t('jbx.confirm.text.delete')).then(function() {
    delMerchant(ids.value).then(() => {
      modal.msgSuccess(t('jbx.alert.delete.success'));
      getList();
    }).catch(() => {
      modal.msgError(t('jbx.alert.delete.failure'));
    });
    return Promise.resolve();
  }).catch(() => {});
}

// 查看详情
function handleView(row) {
  detailId.value = row.id;
  openView.value = true;
  detailTitle.value = t('merchant.detail');
}

// 对话框关闭回调
function dialogOfClosedMethods(val) {
  openEdit.value = false;
  openView.value = false;
  if (val) {
    getList();
  }
}

// 初始化数据
getList();
</script>

<style scoped>
.common-card {
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.query-box {
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.queryForm {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
  padding: 15px 0;
}

.btn-form {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style>